
import 'package:flutter/material.dart';

///
/// demo_for_app_lifecycle.dart
///

void main() => runApp(const MaterialApp(home: MyHomePage(),));


///
/// 监听生命周期的变化
///

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {
  @override
  Widget build(BuildContext context) {
    final result = Scaffold(
      appBar: AppBar(title: const Text('生命周期的变化示例'), ),
      body: const Center(
        child: Text('生命周期的变化示例', style: TextStyle(fontSize: 20.0)),
      ),
    );
    return result;
  }

  @override
  @mustCallSuper
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);//注册监听器
  }

  @override
  @mustCallSuper
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);//移除监听器
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) async {
    print("$state");
    if (state == AppLifecycleState.resumed) {
      // do sth
    }
  }
}



